package com.nice.web;

import java.io.IOException;

import org.eclipse.jetty.websocket.WebSocket.OnBinaryMessage;
import org.eclipse.jetty.websocket.WebSocket.OnTextMessage;

import com.nice.controller.MessageDispatch;
import com.nice.message.Message;
import com.nice.message.MessageHandler;

class WebMsgHandler implements OnBinaryMessage, OnTextMessage, MessageHandler {

	private MessageDispatch msgCenter = MessageDispatch.getInstance();
	private Connection _connection;
	private int clientId;

	@Override
	public void onClose(int closeCode, String message) {
		msgCenter.remove(clientId);
	}

	@Override
	public void onMessage(String data) {
		onMessage(data.getBytes(), 0, data.length());
	}

	@Override
	public void onOpen(Connection connection) {
		_connection = connection;
	}

	@Override
	public void onMessage(byte[] data, int offset, int len) {
		Message from = Message.from(data, offset, len);
		from.sender = this;
		msgCenter.dispatch(from);
	}

	@Override
	public void handle(Message msg) {
		try {
			byte[] b = msg.toByte().array();
			_connection.sendMessage(b, 0, b.length);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void doExit(Message exitMsg) {
		msgCenter.remove(clientId);
	}
}